package com.sihai.ehr.web.action.invite;

import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;

import com.sihai.core.LimitedList;
import com.sihai.core.beans.BeanInject;
import com.sihai.ehr.model.biz.AuditType;
import com.sihai.ehr.model.biz.Duty;
import com.sihai.ehr.model.biz.Grade;
import com.sihai.ehr.model.biz.InviteApply;
import com.sihai.ehr.model.biz.InviteApplyAuditing;
import com.sihai.ehr.model.biz.InviteArrange;
import com.sihai.ehr.model.biz.InviteFashion;
import com.sihai.ehr.model.biz.JobSpecification;
import com.sihai.ehr.model.sys.AuditStatus;
import com.sihai.ehr.model.sys.InviteEnum;
import com.sihai.ehr.model.sys.InviteFashionEnum;
import com.sihai.ehr.model.sys.InvitePageEnum;
import com.sihai.ehr.model.sys.Organization;
import com.sihai.ehr.service.DutyService;
import com.sihai.ehr.service.GradeService;
import com.sihai.ehr.service.InviteService;
import com.sihai.ehr.service.JobSpecificationService;
import com.sihai.ehr.service.OrganizationService;
import com.sihai.ehr.utils.DateUtil;
import com.sihai.ehr.web.action.EHRAction;
import com.sihai.ehr.web.pojo.InviteArrangePojo;

/**
 * 招聘管理控制器
 * 
 * @author Henry-PC
 */
@Results({
		@Result(name = "invite_list", location = "invite_main.jsp"),
		@Result(name = "invite_apply_list", location = "invite_apply_list.jsp"),
		@Result(name = "invite_audit_list", location = "invite_audit_list.jsp"),
		@Result(name = "invite_browse", location = "invite_browse.jsp"),
		@Result(name = "invite_arrange_list", location = "invite_arrange_list.jsp"),
		@Result(name = "invite_apply", location = "invite_apply.jsp"),
		@Result(name = "invite_fashion", location = "invite_fashion.jsp"),
		@Result(name = "invite_arrange", location = "invite_arrange.jsp"),
		@Result(name = "invite_audit", location = "invite_audit.jsp") })
public class InviteFormAction extends EHRAction {

	Log log = LogFactory.getLog(InviteFormAction.class);
	/**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = -2942351308676108284L;

	/**********************************
	 * ---------service interface------
	 *********************************/
	/**
	 * 组织结构服务
	 */
	@BeanInject
	private OrganizationService organizationService;

	/**
	 * 职务服务
	 */
	@BeanInject
	private DutyService dutyService;

	/**
	 * 招聘服务
	 */
	@BeanInject
	private InviteService inviteService;

	@BeanInject
	private GradeService gradeService;

	@BeanInject
	private JobSpecificationService jobSpecificationService;

	/**********************************
	 * ---------page properties-------
	 *********************************/
	/**
	 * 组织架构Bean
	 */
	private Organization organization;
	/**
	 * 组织架构列表
	 */
	private List<Organization> organizations;

	/**
	 * 招聘ID
	 */
	private Long inviteId;
	/**
	 * 页面编号
	 */
	private String p;
	/**
	 * 功能模块
	 */
	private String module;
	/**
	 * 职务ID
	 */
	private Long dutyId;
	/**
	 * 职务Bean
	 */
	private Duty duty;
	/**
	 * 职务列表
	 */
	private List<Duty> dutys;
	/**
	 * 职级ID
	 */
	private Long gradeId;

	private Long gradeLvId;

	private List<Grade> grades;

	private List<Grade> gradeLvs;

	/**
	 * 招聘申请Bean
	 */
	private InviteApply inviteApply;

	/**
	 * 招聘申请Bean列表
	 */
	private LimitedList<InviteApply> inviteApplies;

	/**
	 * 是否发生异常
	 */
	private boolean isError = false;

	/**
	 * 移出的招聘申请ID集合
	 */
	private String ids;

	private String title;
	/**
	 * add,delete,modify
	 */
	private String operation;

	/**
	 * 面试安排结果枚举
	 */
	private String inviteArrangeResult;

	/*****************************************
	 * ------------------招聘安排----------------
	 *****************************************/
	/**
	 * 招聘安排
	 */
	private InviteArrange inviteArrange;
	/**
	 * 招聘安排列表
	 */
	LimitedList<InviteArrangePojo> inviteArranges;
	/**
	 * 渠道编号
	 */
	private Long inviteFashionId;
	/**
	 * 招聘渠道
	 */
	private InviteFashion inviteFashion;
	/**
	 * 招聘渠道列表
	 */
	private LimitedList<InviteFashion> inviteFashions;

	// -----------------招聘申请审核模块-----------------
	private List<List<InviteApplyAuditing>> audits;

	private JobSpecification jobSpecification;

	@Action("/invite/invite_list")
	public String execute() throws Exception {
		try {
			// 根据传值PageNo获取页面标题及页面内容地址
			listTitle = InvitePageEnum.valueOf(p).getListTitle();
			listAction = InvitePageEnum.valueOf(p).getUrl();
			module = InvitePageEnum.valueOf(p).getBundle();
			showChildOrg = true;
			organizations = organizationService.findChildren(null, true, null,
					null);
			if (organizations != null && organizations.size() > 0) {
				if(getCurrentUserId() > 0){
	            	Long topOrgId = getCurrentUser().getWork().getOrganization().getTopOrganization().getId();
	            	Iterator<Organization> it = organizations.iterator();
	            	while(it.hasNext()){
	            		Organization o = it.next();
	            		if(o.getId() != topOrgId){
	            			it.remove();
	            		}
	            	}
	            }
				organizationId = organizations.get(0).getId();
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		return "invite_list";
	}

	/**
	 * 请求招聘申请列表页面
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action("/invite/invite_apply_list")
	public String getInviteList() throws Exception {
		try {
			inviteApplies = inviteService.searchInviteAppliesByAuditStatus(organizationId,
					dutyId, AuditStatus.wait_audit, createLimit(), createSorter());
			/* 分页 */
			this.paging(inviteApplies);
			/* 设置翻页action */
			this.setPageUrl("invite/invite_apply_list.xhtml");
		} catch (Exception e) {
			// TODO: handle exception
		}
		return "invite_apply_list";
	}

	/**
	 * 提交招聘渠道
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action("/invite/invite_fashion")
	public String handleInviteFashion() throws Exception {
		if (ids == null || ids.isEmpty() || operation == null) {
			if (log.isErrorEnabled()) {
				isError = true;
				return "invite_arrange_list"; // 招聘安排列表
			}
		}

		try {
			if (operation.equals("modify")) {
				listTitle = "修改";
				inviteFashion = new InviteFashion();
				inviteFashion
						.setChannel(inviteService.getInviteArrangeByApplyId(
								Long.parseLong(ids.split("-")[1])).getChannel());
			}else{
				listTitle = "添加";
			}
			return "invite_fashion";
		} catch (Exception e) {
			return ERROR;
		}

	}

	/**
	 * 提交招聘申请
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action("/invite/post_apply")
	public String postApply() throws Exception {
		if (inviteApply == null) {
			if (log.isErrorEnabled()) {
				isError = true;
				return "invite_apply";
			}
		}
		if (getParameter("apply_date") != null) {
			inviteApply.setApplyDate(DateUtil
					.parseDate(getParameter("apply_date")));
		}
		// 添加招聘申请对象
		try {
			inviteApply.setAuditStatus(AuditStatus.wait_audit);
			inviteService.saveInviteApply(inviteApply);

		} catch (Exception e) {
			isError = true;
			if (log.isErrorEnabled()) {
				log.error("【添加招聘申请发生异常】");
			}
			return ERROR;
		}
		return "invite_apply";
	}

	/**
	 * 提交招聘渠道
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action("/invite/post_fashion")
	public String postFashionInfo() throws Exception {
		if (inviteFashion == null) {
			if (log.isErrorEnabled()) {
				isError = true;
				return ERROR;
			}
		}

		// 流程修改 2012-07-19
		if (inviteFashion.getChannel() == null
				&& inviteFashion.getChannel().isEmpty()) {
			if (log.isErrorEnabled()) {
				isError = true;
				return ERROR;
			}
		}
		// 修改
		if (operation != null && operation.equals("modify")) {
			if (ids != null && !ids.isEmpty()) {
				try {
					InviteArrange mArrange;
					for (String s : ids.split(",")) {
						mArrange = inviteService.getInviteArrangeByApplyId(Long
								.parseLong(s.split("-")[1]));
						if (mArrange == null) {
							mArrange = new InviteArrange();
							mArrange.setInviteApply(inviteService.getInviteApply(Long
									.parseLong(s.split("-")[1])));
							mArrange.setInviteResult(InviteEnum.arrangement);
						}
						mArrange.setChannel(inviteFashion.getChannel());
						inviteService.saveInviteArrange(mArrange);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		} else {
			if (ids != null && !ids.isEmpty()) {
				try {
					InviteApply mApply;
					for (String s : ids.split(",")) {
						InviteArrange mArrange = inviteService
								.getInviteArrangeByApplyId(Long.parseLong(s
										.split("-")[1]));
						if (mArrange == null) {
							mArrange = new InviteArrange();
						}
						mArrange.setInviteApply(inviteService
								.getInviteApply(Long.parseLong(s.split("-")[1])));
						mArrange.setChannel(inviteFashion.getChannel());
						mArrange.setInviteResult(InviteEnum.arrangement);
						inviteService.saveInviteArrange(mArrange);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return "invite_arrange_list";
	}

	/**
	 * 移出招聘信息ID列表
	 * 
	 * @return
	 */
	@Action(value = "/invite/invite_delete", results = { @Result(name = "success", type = "plainText") })
	public String removeInviteByIds() throws Exception {
		try {
			inviteService.removeInviteApplys(ids);
		} catch (Exception e) {
			if (log.isErrorEnabled()) {
				log.error("【移除招聘申请发生异常】");
			}
			return ERROR;
		}
		return SUCCESS;
	}

	/**
	 * 移动招聘安排
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action(value = "/invite/invite_delete_arrange", results = { @Result(name = "success", type = "plainText") })
	public String removeInviteArrangeByIds() throws Exception {

		try {
			inviteService.removeInviteArranges(ids);
		} catch (Exception e) {
			if (log.isErrorEnabled()) {
				log.error("【移除招聘安排申请发生异常】［错误原因：" + e.getMessage() + "］");
			}
			return ERROR;
		}
		return SUCCESS;
	}

	/**
	 * 处理招聘申请及修改方法入口
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action(value = "/invite/invite_apply")
	public String handleInviteApply() throws Exception {
		// 检测是否是修改申请
		if (getParameter("inviteId") != null) {
			title = "修改";
			try {
				inviteApply = inviteService.getInviteApply(Long
						.parseLong(getParameter("inviteId")));
				organizationId = inviteApply.getOrganization().getId();
				// organizations = organizationService.findAllChildren(false,
				// null, null);
				dutyId = inviteApply.getDuty().getId();
				dutys = dutyService.search(organizationId, null, null);

				Duty vDuty = new Duty();
				vDuty.setId(dutyId);
				Grade vGrade = new Grade();
				vGrade.setDuty(vDuty);
				// 职等
				grades = gradeService.search(dutyId, "gradeName", null, null);
				// 职级
				if (grades != null && grades.size() > 0) {
					vGrade.setGradeName(grades.get(0).getGradeName());
					gradeLvs = gradeService.search(vGrade, null, null);
				}
				if (inviteApply.getGrade() != null) {
					gradeId = inviteApply.getGrade().getId();
				}
				if (inviteApply.getGradeLevel() != null) {
					gradeLvId = inviteApply.getGradeLevel().getId();
				}

			} catch (Exception e) {
				if (log.isErrorEnabled()) {
					log.error("【读取招聘申请发生异常】");
				}
				return ERROR;
			}
		} else {
			title = "添加";
			// 添加招聘申请

			organizationId = -1l;
			dutyId = -1l;
			gradeId = -1l;
			gradeLvId = -1l;
			inviteApply = new InviteApply();
			inviteApply.setApplyDate(new Date());
			// organizations = organizationService.findAllChildren(false, null,
			// null);
			// if (organizations != null && organizations.size() > 0) {
			// organizationId = organizations.get(0).getId();
			// dutys = dutyService.search(organizationId, null, null);
			// if (dutys != null && dutys.size() > 0) {
			// dutyId = dutys.get(0).getId();
			// Duty vDuty = new Duty();
			// vDuty.setId(dutyId);
			// Grade vGrade = new Grade();
			// vGrade.setDuty(vDuty);
			// // 职等
			// grades = gradeService.search(dutyId, "gradeName", null,
			// null);
			//
			// // 职级
			// if (grades != null && grades.size() > 0) {
			// vGrade.setGradeName(grades.get(0).getGradeName());
			// gradeLvs = gradeService.search(vGrade, null, null);
			// }
			// }
			// }
		}
		return "invite_apply";
	}

	/**
	 * 招聘安排处理
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action(value = "/invite/invite_arrange")
	public String handleInviteArrange() throws Exception {
		// 检测是否是修改申请
		if (getParameter("arrangeId") != null) {
			title = "修改";
			try {
				inviteArrange = inviteService.getInviteArrange(Long
						.parseLong(getParameter("arrangeId")));
				organizationId = inviteArrange.getInviteApply()
						.getOrganization().getId();
				organizations = organizationService.findAllChildren(true, null,
						null);
				inviteApplies = inviteService.searchInviteApplies(
						organizationId, 0L, null, null);
				inviteFashions = inviteService.searchFashions("", null, null);

			} catch (Exception e) {
				if (log.isErrorEnabled()) {
					log.error("【读取安排发生异常】");
				}
				return ERROR;
			}
		} else {
			title = "添加";
			// 添加招聘申请
			organizations = organizationService.findAllChildren(true, null,
					null);
			if (organizations != null && organizations.size() > 0) {
				organizationId = organizations.get(0).getId();
				inviteApplies = inviteService.searchInviteApplies(
						organizationId, 0L, null, null);
			}
			inviteFashions = inviteService.searchFashions("", null, null);
		}
		return "invite_arrange";
	}

	/**
	 * 招聘审核
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action("/invite/invite_audit_list")
	public String queryInviteAuditList() throws Exception {
		try {
			inviteApplies = inviteService.searchInviteAppliesByNotPassAudit(
					organizationId, dutyId, createLimit(), createSorter());
			/* 分页 */
			this.paging(inviteApplies);
			/* 设置翻页action */
			this.setPageUrl("invite/invite_audit_list.xhtml");
		} catch (Exception e) {
			// TODO: handle exception
		}
		return "invite_audit_list";
	}

	/**
	 * 招聘浏览
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action("/invite/invite_browse")
	public String queryInviteBrowseList() throws Exception {
		try {
			inviteApplies = inviteService.searchInviteAppliesByPassAudit(
					organizationId, dutyId, createLimit(), createSorter());
			/* 分页 */
			this.paging(inviteApplies);
			/* 设置翻页action */
			this.setPageUrl("invite/invite_browse.xhtml");
		} catch (Exception e) {
			// TODO: handle exception
		}
		return "invite_browse";
	}

	/**
	 * 招聘安排列表
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action("/invite/invite_arrange_list")
	public String queryInviteArrangeList() throws Exception {
		try { // getParameter("page");
			inviteArranges = inviteService.searchInviteArranges(
					organizationId,
					dutyId,
					inviteArrangeResult == null
							|| inviteArrangeResult.equals("-1") ? null
							: InviteEnum.valueOf(inviteArrangeResult),
					createLimit(), createSorter());
			for (Iterator iterator = inviteArranges.iterator(); iterator
					.hasNext();) {
				InviteArrangePojo vPojo = (InviteArrangePojo) iterator.next();
				vPojo.setOrganization(organizationService.get(vPojo.getOrgId()));
			}
			/* 分页 */
			this.paging(inviteArranges);
			/* 设置翻页action */
			this.setPageUrl("invite/invite_arrange_list.xhtml");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "invite_arrange_list";
	}

	/**
	 * 提交招聘安排
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action("/invite/post_arrange")
	public String postInviteArrange() throws Exception {
		if (inviteArrange == null) {
			if (log.isErrorEnabled()) {
				isError = true;
				return "invite_arrange";
			}
		}
		// 添加招聘渠道对象
		try {
			if (inviteArrange.getId() == null || inviteArrange.getId() <= 0) {
				inviteArrange.setInviteResult(InviteEnum.not_scheduled);
			}
			inviteService.saveInviteArrange(inviteArrange);
		} catch (Exception e) {
			isError = true;
			if (log.isErrorEnabled()) {
				log.error("【添加招聘渠道发生异常】");
			}
			return ERROR;
		}
		return "invite_arrange";
	}

	/**
	 * 招聘申请审核处理
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action("/invite/invite_audit")
	public String handleInviteApplyAuditing() throws Exception {

		listTitle = "新员工招聘审核";
		if (inviteId == null) {
			return ERROR;
		}
		try {

			inviteApply = inviteService.getInviteApply(inviteId);
			if (inviteApply == null) {
				return ERROR;
			}
			List<JobSpecification> jobSpecifications = jobSpecificationService
					.findByDuty(inviteApply.getDuty().getId(), null, null);
			if (jobSpecifications != null && jobSpecifications.size() > 0) {
				jobSpecification = jobSpecifications.get(0);
			}

			audits = inviteService.searchApplyAuditings(inviteApply.getId(),
					null, null);
			if (audits == null || audits.isEmpty()) {
				inviteService.saveInviteApplyAuditingProcess(inviteApply, 1);
				audits = inviteService.searchApplyAuditings(
						inviteApply.getId(), null, null);
			}
            //检查当前登录用户是否可以审核当前结点
            if(inviteApply.getDuty() != null && audits != null && !audits.isEmpty()){
                checkCanAudit(inviteApply.getDuty(), audits.get(audits.size()-1));
            }
		} catch (Exception e) {
			e.printStackTrace(); // To change body of catch statement use File |
			// Settings | File Templates.
			throw new RuntimeException(e.getMessage());
		}
		currentAuditType = AuditType.audit_invite_apply.toString();
		return "invite_audit";
	}

	/**
	 * *********************************** --------------properites-------------
	 * ************************************
	 */

	public Organization getOrganization() {
		return organization;
	}

	public void setOrganization(Organization organization) {
		this.organization = organization;
	}

	public List<Organization> getOrganizations() {
		return organizations;
	}

	public void setOrganizations(List<Organization> organizations) {
		this.organizations = organizations;
	}

	public Long getInviteId() {
		return inviteId;
	}

	public void setInviteId(Long inviteId) {
		this.inviteId = inviteId;
	}

	public String getP() {
		return p;
	}

	public void setP(String p) {
		this.p = p;
	}

	public Long getDutyId() {
		return dutyId;
	}

	public void setDutyId(Long dutyId) {
		this.dutyId = dutyId;
	}

	public Duty getDuty() {
		return duty;
	}

	public void setDuty(Duty duty) {
		this.duty = duty;
	}

	public List<Duty> getDutys() {
		return dutys;
	}

	public void setDutys(List<Duty> dutys) {
		this.dutys = dutys;
	}

	public Long getGradeId() {
		return gradeId;
	}

	public void setGradeId(Long gradeId) {
		this.gradeId = gradeId;
	}

	public Long getGradeLvId() {
		return gradeLvId;
	}

	public void setGradeLvId(Long gradeLvId) {
		this.gradeLvId = gradeLvId;
	}

	public List<Grade> getGrades() {
		return grades;
	}

	public void setGrades(List<Grade> grades) {
		this.grades = grades;
	}

	public List<Grade> getGradeLvs() {
		return gradeLvs;
	}

	public void setGradeLvs(List<Grade> gradeLvs) {
		this.gradeLvs = gradeLvs;
	}

	public LimitedList<InviteApply> getInviteApplies() {
		return inviteApplies;
	}

	public void setInviteApplies(LimitedList<InviteApply> inviteApplies) {
		this.inviteApplies = inviteApplies;
	}

	public boolean isError() {
		return isError;
	}

	public void setError(boolean error) {
		isError = error;
	}

	public String getIds() {
		return ids;
	}

	public void setIds(String ids) {
		this.ids = ids;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getOperation() {
		return operation;
	}

	public void setOperation(String operation) {
		this.operation = operation;
	}

	public InviteApply getInviteApply() {
		return inviteApply;
	}

	public void setInviteApply(InviteApply inviteApply) {
		this.inviteApply = inviteApply;
	}

	public String getModule() {
		return module;
	}

	public void setModule(String module) {
		this.module = module;
	}

	public String getInviteArrangeResult() {
		return inviteArrangeResult;
	}

	public void setInviteArrangeResult(String inviteArrangeResult) {
		this.inviteArrangeResult = inviteArrangeResult;
	}

	public InviteArrange getInviteArrange() {
		return inviteArrange;
	}

	public void setInviteArrange(InviteArrange inviteArrange) {
		this.inviteArrange = inviteArrange;
	}

	public LimitedList<InviteArrangePojo> getInviteArranges() {
		return inviteArranges;
	}

	public void setInviteArranges(LimitedList<InviteArrangePojo> inviteArranges) {
		this.inviteArranges = inviteArranges;
	}

	public Long getInviteFashionId() {
		return inviteFashionId;
	}

	public void setInviteFashionId(Long inviteFashionId) {
		this.inviteFashionId = inviteFashionId;
	}

	public InviteFashion getInviteFashion() {
		return inviteFashion;
	}

	public void setInviteFashion(InviteFashion inviteFashion) {
		this.inviteFashion = inviteFashion;
	}

	public LimitedList<InviteFashion> getInviteFashions() {
		return inviteFashions;
	}

	public void setInviteFashions(LimitedList<InviteFashion> inviteFashions) {
		this.inviteFashions = inviteFashions;
	}

	public List<List<InviteApplyAuditing>> getAudits() {
		return audits;
	}

	public void setAudits(List<List<InviteApplyAuditing>> audits) {
		this.audits = audits;
	}

	public JobSpecification getJobSpecification() {
		return jobSpecification;
	}

	public void setJobSpecification(JobSpecification jobSpecification) {
		this.jobSpecification = jobSpecification;
	}
}
